package com.acerola.downloader.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @program: MultithreadedDownloader
 * @description: 获取文件地址
 * @author: Acerola
 * @create: 2022-05-10 20:27
 **/
public class HttpUtils {
    private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * 获取下载文件大小
     * @param url 下载链接
     * @return
     */
    public static long getHttpFileContentLength(String url) {
        int contentLength = 0;
        HttpURLConnection urlConnection = null;
        try {
            urlConnection = getURLConnection(url);
            contentLength = urlConnection.getContentLength();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }

        }
        return contentLength;
    }

    /**
     * 分块下载
     *
     * @param url      下载地址
     * @param startPos 下载文件起始位置
     * @param endPos   下载文件的结束位置
     * @return
     */

    public static HttpURLConnection getURLConnection(String url, long startPos, long endPos) throws IOException {
        HttpURLConnection httpURLConnection = getURLConnection(url);
        logger.info("下载的区间是: {}-{}", startPos, endPos);
        if (endPos != 0) {
            httpURLConnection.setRequestProperty("RANGE", "bytes=" + startPos + "-" + endPos);
        } else {
            httpURLConnection.setRequestProperty("RANGE", "bytes=" + startPos + "-");
        }
        return httpURLConnection;
    }

    public static HttpURLConnection getURLConnection(String url) throws IOException {
        URL httpUrl = new URL(url);
        HttpURLConnection httpURLConnection = (HttpURLConnection) httpUrl.openConnection();
        httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko)Chrome/14.0.835.163 Safari/535.1");
        return httpURLConnection;
    }

    public static String getHttpFileName(String url) {
        int index0 = url.lastIndexOf("/");
        int index1 = url.lastIndexOf("?");
        if (index1 == -1) {
            return url.substring(index0 + 1);

        } else {
            return url.substring(index0 + 1, index1);
        }
    }

}
